package cn.hpclub.server.controller.admin;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.upload.UploadFile;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.util.SystemConfigUtil;
import cn.hpclub.server.util.UploadFileUtil;

@Before(value = { POST.class })
public class CommonController<M extends Model<M>> extends Controller{
    private static Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * @Title: upload
     * @Description:保存客户端上传图片 void
     */
    @ActionKey("/common/VPFileUpload")
    public void upload(){
        log.info("upload");
        String response = "";
        try{
            checkParameter(getPara("action"), getPara("appid"));
            UploadFile upfile = getUploadFile();
            String fileName = upfile.getFileName();
            String fileSuffix = StringUtils.substringAfterLast(fileName, ".").toLowerCase();
            checkFileType(fileSuffix);
            File uploadFile = upfile.getFile();
            long fileLength = uploadFile.length();
            checkUploadFileSize(fileLength);
            String uploadFilePath = UploadFileUtil.saveImage(uploadFile);
            response = getResponse(fileName, fileSuffix, fileLength, uploadFilePath);
        }
        catch(IOException e){
            e.printStackTrace();
            response = repsoneError(e.getMessage());
        }
        catch(Exception e){
            e.printStackTrace();
            response = repsoneError("服务器内部错误");
        }
        renderJson(response);
    }

    /**
     * @Title: getResponse
     * @Description:获取客户段响应数据
     * @param fileName
     *            上传文件名
     * @param fileSuffix
     *            文件后缀
     * @param fileSize
     *            文件大小
     * @param filePath
     *            文件路径
     * @return String
     */
    private String getResponse(String fileName, String fileSuffix, long fileSize, String filePath){
        JSONObject jo = new JSONObject().put("status", 1).put("msg", "上传文件成功！").put("name", fileName)
                .put("path", filePath).put("thumb", filePath).put("size", fileSize).put("ext", fileSuffix);
        log.debug(jo.toString());
        return jo.toString();
    }

    /**
     * @Title: getUploadFile
     * @Description:获取上传文件对象
     */
    private UploadFile getUploadFile() throws IOException{
        UploadFile upfile = getFile();
        if(upfile == null){
            log.error("params is error.return.");
            throw new IOException("参数错误，上传文件为空！");
        }
        return upfile;
    }

    /**
     * @Title: checkUploadFileSize
     * @Description:检查上传文件大小，如果达到系统设定上限，抛出异常
     * @param fileSize
     *            文件大小
     */
    private void checkUploadFileSize(long fileSize) throws IOException{
        int uploadLimit = SystemConfigUtil.getSystemConfig().getUploadLimit() * 102400;
        log.info("uploadLimit=" + uploadLimit + ",uploadFileSize=" + fileSize);
        if(uploadLimit != 0 && fileSize > uploadLimit){
            log.error("upload.length is null or length is out size.");
            throw new IOException("文件超度超过系统上限，不能保存该图片！");
        }
    }

    /**
     * @Title: checkFileType
     * @Description:检查文件类型
     * @param fileSuffix
     *            文件后缀
     */
    private void checkFileType(String fileSuffix) throws IOException{
        boolean result = false;
        String allowedImageFileType = SystemConfigUtil.getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
        if(StringUtils.isEmpty(allowedImageFileType)){
            log.error("allowedImageFileType is empty");
            result = true;
        }
        String[] fileExtensionArray = allowedImageFileType.split(SystemConfig.EXTENSION_SEPARATOR);
        if(!ArrayUtils.contains(fileExtensionArray, fileSuffix)){
            log.error("fileExtensionArray=" + fileExtensionArray + ".fileExtension=" + fileSuffix + ",return.");
            result = true;
        }
        if(result){
            throw new IOException("文件格式不支持!");
        }
    }

    /**
     * @Title: checkParameter
     * @Description:检查接口参数
     * @param action
     *            操作类型
     * @param appid
     *            应用ID
     */
    private void checkParameter(String action, String appid) throws IOException{
        if(StrKit.isBlank(action)){
            log.info("action is null. do default action:UpLoadImage");
            return;
        }
        if(!"UpLoadImage".equals(action)){
            throw new IOException("参数错误");
        }
        // if(!Constant.DZG_APPID.equals(appid)){
        // throw new IOException("appID错误，非大掌柜应用");
        // }
    }

    /**
     * @Title: repsoneError
     * @Description:返回错误响应数据
     */
    private String repsoneError(String msg){
        return new JSONObject().put("status", 0).put("msg", msg).toString();
    }
}